package com.adong.springboot.controller;

import com.adong.springboot.entity.User;
import com.adong.springboot.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;

@RestController
public class UserController {
    @Autowired
    UserRepository userRepository;

    @GetMapping("user/{id}")
    public User getUser(@PathVariable("id") Integer id) {
        Optional<User> userOptional = userRepository.findById(id);
        // 判断查询结果是否为空
        if (userOptional.isPresent()) {
            // 获得查询结果
            User user = userOptional.get();
            System.out.println(user);
            return user;
        }
        return null;
    }

    //http://localhost:8080/user?lastName=xxx&email=xx 插入属性成功
    @GetMapping("/user")
    public User InsertUser(User user) {
        User save = userRepository.save(user);
        return save;
    }
}
